package com.qfedu.knowledge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.util.StringUtil;
import com.qfedu.knowledge.dao.DictValueDao;
import com.qfedu.knowledge.entity.bo.DictValueBO;
import com.qfedu.knowledge.entity.dto.DictDTO;
import com.qfedu.knowledge.entity.enums.ResultEnum;
import com.qfedu.knowledge.exception.BusinessRuntimeException;
import com.qfedu.knowledge.iterator.Iterator;
import com.qfedu.knowledge.service.IDictValueService;
import com.qfedu.knowledge.util.ListUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName DictValueServiceImpl
 * @Author ykx
 * @Date 2024/1/9 15:55
 * @Version 1.0
 */
@Service
public class DictValueServiceImpl extends ServiceImpl<DictValueDao, DictValueBO> implements IDictValueService {
    /**
     * 根据itemCode获取字典列表
     *
     * @param itemCode itemCode
     * @return List<DictValueBO>
     */
    @Override
    public List<DictValueBO> getDictListByItemCode(String itemCode) {
        QueryWrapper<DictValueBO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtil.isNotEmpty(itemCode), "item_code", itemCode);
        return list(queryWrapper);
    }

    @Override
    public Boolean addDict(DictDTO dictDTO) {
        // 检查数组长度是否规范
        boolean sameLength = ListUtils.isSameLength(dictDTO.getValueCodeList(), dictDTO.getValueNameList());
        if (!sameLength) {
            throw new BusinessRuntimeException(ResultEnum.LENGTH_ERROR);
        }

        List<DictValueBO> dictValueBOS = new ArrayList<>();
        Iterator iterator = dictDTO.createIterator();
        int index = 0;
        while (iterator.hasNext()) {
            DictValueBO dictValueBO = new DictValueBO();
            dictValueBO.setItemCode(dictDTO.getItemCode());
            dictValueBO.setValueCode((String) iterator.next());
            dictValueBO.setValueName(dictDTO.getValueNameList().get(index++));
            dictValueBOS.add(dictValueBO);
        }
        return saveBatch(dictValueBOS);
    }
}
